package cn.javaex.hgo.action.system.service.hgo_menu_info;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.javaex.hgo.action.system.dao.hgo_menu_info.IHgoMenuInfoDAO;
import cn.javaex.hgo.action.system.dao.hgo_role_info.IHgoRoleInfoDAO;
import cn.javaex.hgo.action.system.dao.hgo_role_menu.IHgoRoleMenuDAO;
import cn.javaex.hgo.action.system.view.HgoMenuInfo;
import cn.javaex.hgo.config.constant.HgoErrorMsg;
import cn.javaex.hgo.config.exception.HgoException;

@Service("HgoMenuInfoService")
public class HgoMenuInfoService {
	
	@Autowired
	private IHgoMenuInfoDAO iHgoMenuInfoDAO;
	@Autowired
	private IHgoRoleMenuDAO iHgoRoleMenuDAO;
	@Autowired
	private IHgoRoleInfoDAO iHgoRoleInfoDAO;
	
	/**
	 * 保存菜单
	 * @param HgoMenuInfo
	 * @throws HgoException
	 */
	public void save(HgoMenuInfo hgoMenuInfo) throws HgoException {
		// 1.0 校验按钮权限标识是否重复
		if (StringUtils.isNotEmpty(hgoMenuInfo.getType())) {
			int count = iHgoMenuInfoDAO.countByPermCode(hgoMenuInfo.getPermCode(), hgoMenuInfo.getId());
			if (count>0) {
				throw new HgoException(HgoErrorMsg.ERROR_100010);
			}
		}
		
		// 2.0 新增或更新
		if (StringUtils.isEmpty(hgoMenuInfo.getId())) {
			// 新增
			hgoMenuInfo.setIsSystem(0);
			iHgoMenuInfoDAO.insert(hgoMenuInfo);
		} else {
			// 更新
			iHgoMenuInfoDAO.update(hgoMenuInfo);
		}
	}
	
	/**
	 * 根据id查询菜单信息
	 * @param id 主键
	 * @return
	 */
	public HgoMenuInfo selectById(String id) {
		return iHgoMenuInfoDAO.selectById(id);
	}
	
	/**
	 * 根据父节点id，查询菜单列表
	 * @param parentId
	 * @return
	 */
	public List<HgoMenuInfo> listByParentId(String parentId) {
		return iHgoMenuInfoDAO.listByParentId(parentId);
	}
	
	/**
	 * 查询所有菜单
	 * @return
	 */
	public List<HgoMenuInfo> list() {
		// 1.0 获取全部菜单
		List<HgoMenuInfo> allList = iHgoMenuInfoDAO.list();
		// 2.0 定义一个map
		Map<String, HgoMenuInfo> itemMap = new HashMap<String, HgoMenuInfo>(allList.size());
		// 3.0 定义一级菜单list
		List<HgoMenuInfo> parentMenuList = new ArrayList<HgoMenuInfo>();
	
		// 4.0 遍历全部菜单list
		if (allList!=null && allList.isEmpty()==false) {
			// 4.1 第一次遍历，取出1级菜单
			for (HgoMenuInfo hgoMenuInfo : allList) {
				// 设置map
				itemMap.put(hgoMenuInfo.getId(), hgoMenuInfo);
				
				if ("-1".equals(hgoMenuInfo.getParentId())) {
					parentMenuList.add(hgoMenuInfo);
				}
			}
			// 4.2 第二次遍历，取出每个1级菜单下的子菜单
			for (HgoMenuInfo hgoMenuInfo : allList) {
				if (!"-1".equals(hgoMenuInfo.getId())) {
					HgoMenuInfo parent = itemMap.get(hgoMenuInfo.getParentId());
					if (parent!=null) {
						parent.getChildrenList().add(hgoMenuInfo);
					}
				}
			}
		}
	
		return parentMenuList;
	}

	/**
	 * 删除菜单
	 * @param id 菜单id
	 * @throws HgoException
	 */
	public void deleteById(String id) throws HgoException {
		// 1.0 校验该菜单是否已被角色分配了
		List<Integer> roleIdList = iHgoRoleMenuDAO.listRoleIdByMenuId(id);
		if (roleIdList!=null && roleIdList.isEmpty()==false) {
			// 1.1 根据角色id，查询角色名称
			List<String> roleNameList = iHgoRoleInfoDAO.listNameByIdList(roleIdList);
			if (roleNameList!=null && roleNameList.isEmpty()==false) {
				String str = "";
				for (String roleName : roleNameList) {
					str += roleName + "、";
				}
				str = str.substring(0, str.length()-1);
				
				throw new HgoException("该菜单已被以下角色分配，无法删除："+str);
			}
		}
		
		// 2.0 删除菜单
		iHgoMenuInfoDAO.deleteById(id);
	}

	/**
	 * 查询当前菜单级别下最大排序
	 * @param parentId
	 * @return
	 */
	public int selectMaxSortByParentId(String parentId) {
		int maxSort = 0;
		try {
			maxSort = iHgoMenuInfoDAO.selectMaxSortByParentId(parentId);
		} catch (Exception e) {
			
		}
		return maxSort;
	}

	/**
	 * 获取某个角色下的菜单列表（带回显）
	 * @param roleId 角色id
	 * @return
	 */
	public List<HgoMenuInfo> listByRoleId(String roleId) {
		// 获取该角色的权限菜单
		List<Integer> menuIdList = iHgoRoleMenuDAO.listMenuIdByRoleId(roleId);
		Map<String, Integer> menuIdMap = new HashMap<String, Integer>(menuIdList.size());
		if (menuIdList!=null && menuIdList.isEmpty()==false) {
			for (Integer menuId : menuIdList) {
				menuIdMap.put(String.valueOf(menuId), menuId);
			}
		}
		
		// 1.0 获取全部菜单
		List<HgoMenuInfo> allList = iHgoMenuInfoDAO.list();
		// 2.0 定义一个map
		Map<String, HgoMenuInfo> itemMap = new HashMap<String, HgoMenuInfo>(allList.size());
		// 3.0 定义一级菜单list
		List<HgoMenuInfo> parentMenuList = new ArrayList<HgoMenuInfo>();
		
		// 4.0 遍历全部菜单list
		if (allList!=null && allList.isEmpty()==false) {
			// 4.1 第一次遍历，取出1级菜单
			for (HgoMenuInfo hgoMenuInfo : allList) {
				// 设置map
				itemMap.put(hgoMenuInfo.getId(), hgoMenuInfo);
				
				if ("-1".equals(hgoMenuInfo.getParentId())) {
					parentMenuList.add(hgoMenuInfo);
				}
			}
			// 4.2 第二次遍历，取出每个1级菜单下的子菜单
			for (HgoMenuInfo hgoMenuInfo : allList) {
				if (!"-1".equals(hgoMenuInfo.getId())) {
					if (menuIdMap.get(hgoMenuInfo.getId())!=null) {
						hgoMenuInfo.setChecked(true);
					}
					HgoMenuInfo parent = itemMap.get(hgoMenuInfo.getParentId());
					if (parent!=null) {
						if (menuIdMap.get(parent.getId())!=null) {
							parent.setOpen(true);
						}
						parent.getChildrenList().add(hgoMenuInfo);
					}
				}
			}
		}
		
		return parentMenuList;
	}

	/**
	 * 用户当前用户拥有权限的菜单
	 * @param userId
	 * @return
	 */
	public List<HgoMenuInfo> listByUserId(String userId) {
		// 1.0 查询当前用户有权限的菜单
		List<HgoMenuInfo> userMenuList = iHgoMenuInfoDAO.listByUserId(userId);
		// 2.0 定义一个map
		Map<String, HgoMenuInfo> itemMap = new HashMap<String, HgoMenuInfo>(userMenuList.size());
		// 3.0 定义一级菜单list
		List<HgoMenuInfo> parentMenuList = new ArrayList<HgoMenuInfo>();

		// 4.0 遍历全部用户菜单list
		if (userMenuList!=null && userMenuList.isEmpty()==false) {
			// 4.1 第一次遍历，取出1级菜单
			for (HgoMenuInfo hgoMenuInfo : userMenuList) {
				// 设置map
				itemMap.put(hgoMenuInfo.getId(), hgoMenuInfo);
				
				if ("-1".equals(hgoMenuInfo.getParentId())) {
					parentMenuList.add(hgoMenuInfo);
				}
			}
			// 4.2 第二次遍历，取出每个1级菜单下的子菜单
			for (HgoMenuInfo hgoMenuInfo : userMenuList) {
				if (!"-1".equals(hgoMenuInfo.getId())) {
					HgoMenuInfo parent = itemMap.get(hgoMenuInfo.getParentId());
					if (parent!=null) {
						parent.getChildrenList().add(hgoMenuInfo);
					}
				}
			}
		}
		
		return parentMenuList;
	}

	/**
	 * 保存排序
	 * @param hgoMenuList
	 */
	public void saveSort(List<HgoMenuInfo> hgoMenuList) {
		for (HgoMenuInfo hgoMenuInfo : hgoMenuList) {
			iHgoMenuInfoDAO.update(hgoMenuInfo);
		}
	}
	
}